package com.lonbon.threecameramaster.test;

import static com.lonbon.threecameramaster.test.ApiUtils.setHdmiDisplay;
import static com.lonbon.threecameramaster.test.ApiUtils.setPowerOffTime;
import static com.lonbon.threecameramaster.test.ApiUtils.setPowerOnTime;
import static com.lonbon.threecameramaster.test.ApiUtils.setTime;
import static com.lonbon.threecameramaster.test.ApiUtils.setUsbCamera;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.input.InputManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.InputDevice;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.lonbon.threecameramaster.R;

/**
 * 创百盒子相关api的验证
 *
 *
 */
public class ChuangbaiTestActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "ChuangbaiTestActivity";
    private TextView mTvDeviceInfo,mTvClose,mTvReboot,mTvNavigation,mTvStatusBar,mTvInstall,mTvTime,mTvTimerOpen,mTvTimerCLose,mTvLight,mTvCamera,mTvUnInstall;

    private TextView mTvInfo,mTvCurrentTime;
    private boolean isHiddenNavigation = true;
    private boolean isHiddenStatus = true;

    private boolean isHDIMOn = true;

    //声网权限申请
    private static final int PERMISSION_REQ_ID = 23;
    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.SET_TIME
    };
    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(this, permission) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
            return false;
        }
        return true;
    }

    private String[] data={"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango","Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Strawberry","Cherry","Mango"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chuangbai_test);

        mTvDeviceInfo = findViewById(R.id.tv_device_info);
        mTvDeviceInfo.setOnClickListener(this);
        mTvClose = findViewById(R.id.tv_close);
        mTvClose.setOnClickListener(this);
        mTvReboot = findViewById(R.id.tv_reboot);
        mTvReboot.setOnClickListener(this);
        mTvNavigation = findViewById(R.id.tv_navigation);
        mTvNavigation.setOnClickListener(this);
        mTvStatusBar = findViewById(R.id.tv_status_bar);
        mTvStatusBar.setOnClickListener(this);
        mTvInstall = findViewById(R.id.tv_install);
        mTvInstall.setOnClickListener(this);
        mTvInfo = findViewById(R.id.tv_info);
        mTvCurrentTime = findViewById(R.id.tv_current_time);
        mTvTime = findViewById(R.id.tv_time);
        mTvTime.setOnClickListener(this);
        mTvTimerCLose = findViewById(R.id.tv_close_timer);
        mTvTimerCLose.setOnClickListener(this);
        mTvTimerOpen = findViewById(R.id.tv_open_timer);
        mTvTimerOpen.setOnClickListener(this);
        mTvLight = findViewById(R.id.tv_light);
        mTvLight.setOnClickListener(this);
        mTvCamera = findViewById(R.id.tv_camera);
        mTvCamera.setOnClickListener(this);
        mTvUnInstall = findViewById(R.id.tv_uninstall);
        mTvUnInstall.setOnClickListener(this);

        startThread();

        ArrayAdapter<String> adapter = new ArrayAdapter(ChuangbaiTestActivity.this, android.R.layout.simple_list_item_1,data);

        ListView listView = findViewById(R.id.main_listview);
//        listView.setVerticalScrollBarEnabled(true);
        listView.setAdapter(adapter);

        InputManager inputManager = (InputManager) getSystemService(Context.INPUT_SERVICE);
        int[] devIds = inputManager.getInputDeviceIds();
        for(int devId : devIds){
            InputDevice device = inputManager.getInputDevice(devId);
            if(device != null){
                Log.e("TEST", "Input device name : " + device.getName() + "---- info: " +device.toString());
            }
        }
    }

    private void startThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
               do {
                   try {
                       Thread.sleep(1000);
                       Message message = new Message();
                       message.what = 1;
                       handler.sendMessage(message);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }

               }while (true);
            }
        }).start();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    long time = System.currentTimeMillis();
                    CharSequence format = DateFormat.format("yyyy-MM-dd hh:mm:ss",time);
                    mTvCurrentTime.setText(format);
            }
        }
    };

    @Override
    public void onClick(View v) {
        if(v.getId() ==  R.id.tv_device_info){
            // 如果已经授权，则初始化 RtcEngine 并加入频道
            if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                    checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                    checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID) &&
                    checkSelfPermission(REQUESTED_PERMISSIONS[3], PERMISSION_REQ_ID)) {
                //设备信息
                String model = android.os.Build.MODEL;
                String board = android.os.Build.BOARD;
                String brand = android.os.Build.BRAND;
                String version = android.os.Build.VERSION.RELEASE;
                int width = getApplicationContext().getResources().getDisplayMetrics().widthPixels;

                int height= getApplicationContext().getResources().getDisplayMetrics().heightPixels;

                mTvInfo.setText("设备型号model："+model+"\n" + "设备主板board："+board+"\n" + "设备定制商brand："+brand+"\n" +
                        "序列号：" + ApiUtils.getDeviceSN() + "\n" +
                        "系统版本号：" + version + "\n" +
                        "固件版本号：" + ApiUtils.getVersion() + "\n" +
                        "内核版本号：" + ApiUtils.getKernelVersion() + "\n" +
                        "IP：" + ApiUtils.getIpAddress(getApplicationContext()) + "\n" +
                        "WIFI MAC：" + ApiUtils.getMac(getApplicationContext()) + "\n" +
                        "以太网MAC：" + ApiUtils.getEthernetMacAddress() + "\n"+
                        "分辨率：" + width +"X"+height + "\n");
            } else {
                Toast.makeText(this,"未开启全部权限",Toast.LENGTH_LONG).show();
            }
        }else if (v.getId() ==  R.id.tv_close){
            //关机
            ApiUtils.shutDown(getApplicationContext());
        }else if (v.getId() ==  R.id.tv_reboot){
            //重启
            ApiUtils.reboot(getApplicationContext());
        } else if (v.getId() ==  R.id.tv_navigation){
            //隐藏导航栏
            if (isHiddenNavigation){
                ApiUtils.setNavigation(getApplicationContext(),true);
                isHiddenNavigation = false;
            }else {
                ApiUtils.setNavigation(getApplicationContext(),false);
                isHiddenNavigation = true;
            }
        }else if (v.getId() ==  R.id.tv_status_bar){
            //隐藏状态栏
            if (isHiddenStatus){
                ApiUtils.setStatusBar(getApplicationContext(),true);
                isHiddenStatus = false;
            } else {
                ApiUtils.setStatusBar(getApplicationContext(),false);
                isHiddenStatus = true;
            }
        }else if (v.getId() ==  R.id.tv_install){
            //静默安装
            Toast.makeText(this,"静默安装中...",Toast.LENGTH_LONG).show();
            String path= Environment.getExternalStorageDirectory().getAbsolutePath();
            Log.d(TAG,"install_path="+path);
            apkInstall(path+"/mount_check.apk");

//                if (checkSelfPermission(REQUESTED_PERMISSIONS[3], PERMISSION_REQ_ID)&&
//                        checkSelfPermission(REQUESTED_PERMISSIONS[4], PERMISSION_REQ_ID)){
//                    ApiUtils.install(path+"/mount_check.apk", new InstallAppListener() {
//                        @Override
//                        public void onError(String infoLine) {
//                            Log.d(TAG,"onError="+infoLine);
//                        }
//
//                        @Override
//                        public void onMessage(String infoLine) {
//                            Log.d(TAG,"onMessage="+infoLine);
//
//                        }
//
//                        @Override
//                        public void onResult(int res) {
//                            Log.d(TAG,"onResult="+res);
//
//                        }
//                    });
//                } else {
//                    Toast.makeText(this,"未开启读写权限",Toast.LENGTH_LONG).show();
//                }
        }else if (v.getId() ==  R.id.tv_uninstall){
            Toast.makeText(this,"静默卸载中...",Toast.LENGTH_LONG).show();
            apkUninstall("com.lonbon.qianlinmountmaster");
        }else if (v.getId() ==  R.id.tv_time){
            Toast.makeText(this,"设置系统时间",Toast.LENGTH_LONG).show();
            setTime(getApplicationContext(),System.currentTimeMillis()-60000);
//                if (checkSelfPermission(REQUESTED_PERMISSIONS[5], PERMISSION_REQ_ID)){
//                    ApiUtils.setSysTime(1699701071000L);
//                    Log.d(TAG,"time="+System.currentTimeMillis());
//                } else {
//                    Toast.makeText(this,"未开启设置时间权限",Toast.LENGTH_LONG).show();
//                    //下面为申请权限的方法，下面的onRequestPermissionsResult方法用于验证此方法申请成功或失败（到时会弹出一个对话框给你选择允许拒绝）
//                    //也会导致回调onRequestPermissionsResult方法
//                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SET_TIME},PERMISSION_REQ_ID);
//                }
        }else if (v.getId() ==  R.id.tv_close_timer) {
            Toast.makeText(this,"5s后关机",Toast.LENGTH_LONG).show();
            //设置关机时间
            setPowerOffTime(getApplicationContext(),System.currentTimeMillis() + 5000);
//                Intent intent = new Intent(ChuangbaiTestActivity.this,TimerCloseActivity.class);
//                startActivity(intent);
        }else if (v.getId() ==  R.id.tv_open_timer) {
            Toast.makeText(this,"60s后开机",Toast.LENGTH_LONG).show();
            //设置开机时间
            setPowerOnTime(System.currentTimeMillis() + 30000);
//                Intent intent1 = new Intent(ChuangbaiTestActivity.this,TimerOpenActivity.class);
//                startActivity(intent1);

        }else if (v.getId() ==  R.id.tv_light) {
//设置背光 HDMI亮度无法控制，能控制MIPI、LVDS、eDP等的屏背光
            Toast.makeText(this,"关闭HDMI显示",Toast.LENGTH_LONG).show();
//                setBacklightBrightness(true, 40);

            //配置HDMI显示
            //on:不管有没有插入HDMI都强制显示
            //off:关闭HDMI显示
            //detect:检测到HDMI插入就显示, 否则不显示
            //setHdmiDisplay("on");
            if (isHDIMOn){
                setHdmiDisplay("off");
                isHDIMOn = false;
            } else {
                setHdmiDisplay("on");
                isHDIMOn = true;
            }
            //setHdmiDisplay("detect");

        }else if (v.getId() ==  R.id.tv_camera) {
            //修改USB摄像头旋转方向
            Toast.makeText(this,"修改USB摄像头旋转方向",Toast.LENGTH_LONG).show();
            setUsbCamera(null, true, 0); //全部USB摄像头
            //setUsbCamera("0c45:6367".replace(":", "."), true, 270); //指定USB(vid:pid)摄像头

        }
    }

    /*
      此函数为申请权限的回调方法，无论成功或者失败，都会回调这个方法
      requestCode:上文中提到的请求码
      permissions：申请的权限
      grantResults：申请的结果
   */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_REQ_ID){
            if(grantResults!=null&&grantResults.length>0){
                //判断用户是否授予了这个权限
                if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    ApiUtils.setSysTime(1699701071000L);
                    Log.d(TAG,"time="+System.currentTimeMillis());
                }else {
                    Toast.makeText(this,"您拒绝了设置时间的权限",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //静默安装
    private void apkInstall(String apkFile) {
        new Thread() {
            @Override
            public void run() {
                int result = Shell.run(new String[] {"pm", "install", "-r", "-g", apkFile});
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), String.format("%s安装%s", apkFile, (result == 0) ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }

    private void apkUninstall(String packageName) {
        new Thread() {
            @Override
            public void run() {
                int result = Shell.run(new String[] {"pm", "uninstall", packageName});
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), String.format("%s卸载%s", packageName, (result == 0) ? "成功" : "失败"), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }
}